import { memo , useEffect , useRef , useCallback , useState } from "react";
import { shallowEqual , useDispatch , useSelector } from "react-redux";
import { getTopBannersAction } from "../../store/actionCreators";
import { Carousel } from 'antd';
import {
  BannerWrapped ,
  BannerLeft ,
  BannerRight ,
  BannerControl ,
} from "./style";

export default memo (
  function HTopBanner () {
    // 组件和redux关联：获取数据和进行操作
    const dispatch = useDispatch ();

    // useSelector要求传入俩个参数，参数一是一个回调函数，接收一个state参数。其返回值会成为useSelector的返回值。第二个参数是比较方式，传入shallowEqual可进行浅层比较。
    const { topBanners } = useSelector ( state => {
      return {
        // topBanners : state.get("recommend").get("topBanners") 写法一
        topBanners: state.getIn ( [ "recommend" , "topBanners" ] ) //  getIn要求传入一个可迭代对象，按迭代顺序中的元素作为get的key来读取值，再从值中取下一个迭代元素作为key的值
      }
    } , shallowEqual );

    useEffect (
      () => {
        dispatch ( getTopBannersAction ());
      }
      , [ dispatch ] );
    
    useEffect(
      () => {
        // 预加载
        topBanners.map((item)=>{
          const img = new Image();
          img.importance = "low";
          img.src = item.imageUrl + "?imageView&blur=40x20";
        });
      },[topBanners]
    )
    // 轮播图ref
    const bannerRef = useRef ();
    const [ currentIndex , setCurrentIndex ] = useState ( 0 );

    const bannerChange = useCallback ( ( from , to ) => {
      setCurrentIndex ( to );
    } , [] )

    const bgImageURL = topBanners[ currentIndex ] && topBanners[ currentIndex ].imageUrl + "?imageView&blur=40x20";

    
return (
  <BannerWrapped bgImgURL={ bgImageURL }>
    <div className="banner wrap-v2">
      <BannerLeft>
        <Carousel effect="fade" autoplay ref={ bannerRef } beforeChange={ bannerChange }>
          {
            topBanners.map ( ( item ) => {
              return (
                <div className={ "banner-item" } key={ item.targetId }>
                  <a href="#">
                    <img src={ item.imageUrl } alt={ item.typeTitle }/>
                  </a>
                </div>
              )
            } )
          }
        </Carousel>
      </BannerLeft>
      <BannerRight>
        <a href="https://music.163.com/#/download" className={ "download" } target={ "_blank" }
           rel="noreferrer">下载客户端</a>
      </BannerRight>
      <BannerControl>
        <a className={ "banner-left" } onClick={ () => bannerRef.current.prev () }>上一张</a>
        <a className={ "banner-right" } onClick={ () => bannerRef.current.next () }>下一张</a>
      </BannerControl>
    </div>
  </BannerWrapped>
)
}
)
